﻿using System.Collections.Specialized;

namespace AspAuthentication.Core
{
    /// <summary>
    /// Defines the class ConfigHelper
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// Safes the config read.
        /// </summary>
        /// <param name="entryName">Name of the entry.</param>
        /// <param name="config">The config.</param>
        /// <returns></returns>
        public static string SafeConfigRead(string entryName, NameValueCollection config)
        {
            return SafeConfigRead(entryName, config,null);
        }
        /// <summary>
        /// Safes the config read.
        /// </summary>
        /// <param name="entryName">Name of the entry.</param>
        /// <param name="config">The config.</param>
        /// <param name="defaultValue">The default value</param>
        /// <returns></returns>
        public static string SafeConfigRead(string entryName, NameValueCollection config, string defaultValue)
        {
            var entryValue = defaultValue;
            if (config[entryName] != null)
            {
                entryValue = config[entryName];
            }
            return entryValue;
        }

        /// <summary>
        /// Safes the config int read.
        /// </summary>
        /// <param name="entryName">Name of the entry.</param>
        /// <param name="config">The config.</param>
        /// <param name="defaultValue">The default value</param>
        /// <returns></returns>
        public static int SafeConfigIntRead(string entryName, NameValueCollection config,int defaultValue)
        {
            var entryValue = "";
            if (config[entryName] != null)
            {
                entryValue = config[entryName];
            }
            int result;
            if(!int.TryParse(entryValue, out result))
            {
                result = defaultValue;
            }
            return result;
        }

        /// <summary>
        /// Safes the config boolean read.
        /// </summary>
        /// <param name="entryName">Name of the entry.</param>
        /// <param name="config">The config.</param>
        /// <param name="defaultValue">The default value</param>
        /// <returns></returns>
        public static bool SafeConfigBooleanRead(string entryName, NameValueCollection config, bool defaultValue)
        {
            var entryValue = "";
            if (config[entryName] != null)
            {
                entryValue = config[entryName];
            }
            bool result;
            if (!bool.TryParse(entryValue, out result)) { result = defaultValue; }
            return result;
        }
    }
}
